﻿using System.Collections.Generic;
using System.Linq;
using log4net;
using SmallBusinessKit.DataAccess.Interfaces;
using SmallBusinessKit.Interfaces;
using SmallBusinessKit.Models.Entities;

namespace SmallBusinessKit.Domains
{
    public class CatalogDomain : ICatalogDomain
    {
        #region Properties

        private static readonly ILog _log = LogManager.GetLogger(typeof(CatalogDomain));

        private readonly ICategoryRepository    _categoryRepository;
        private readonly IItemRepository        _itemRepository;

        #endregion

        #region Methods

        public CatalogDomain(ICategoryRepository categoryRepository, IItemRepository itemRepository)
        {
            _categoryRepository = categoryRepository;
            _itemRepository     = itemRepository;
        }

        public IEnumerable<Category> GetCategories(string id)
        {
            var results = _categoryRepository.GetMany(i => i.ParentId == id && i.IsVisible).ToList();

            _log.DebugFormat("Retrieved {0} Categories", results.Count);

            return (results);
        }

        public IEnumerable<Item> GetChildItems(string parentCategoryId)
        {
            var results    = new List<Item>();

            var category = _categoryRepository.Get(i => i.Id == parentCategoryId && i.IsVisible);
            
            if (category.Items.Any())
            {
                results.AddRange(category.Items);

                _log.DebugFormat("Retrieved {0} Items", category.Items.Count);
            }

            // or another way at getting at them...
            //var r = _itemRepository.GetMany(i => i.Categories.Contains(parentCategoryId)).ToList();
            
            return (results);
        }

        public Item GetItem(string id)
        {
            var result = _itemRepository.Get(i => i.Id == id);

            _log.DebugFormat("Retrieved Item - Id/Title : {0} / {1}", result.Id, result.Title);

            return (result);
        }

        #endregion
    }
}
